package com.xpec.c4.h5net;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicInteger;

public class H5XSEPacketCategoryMeter
{
	Timer timer = new Timer();
	
	private static H5XSEPacketCategoryMeter instance = new H5XSEPacketCategoryMeter();
	
	public class ResetTask extends TimerTask{
		
		private H5XSEPacketCategoryMeter meter;
		
		public ResetTask(H5XSEPacketCategoryMeter meter) 
		{
			super();
			this.meter = meter;
		}

		@Override
		public void run() 
		{
			meter.update();
		}		
		
	}
	
	public H5XSEPacketCategoryMeter()
	{
		super();
		timer.schedule(new ResetTask(this), 5000, 5000);
	}

	public static H5XSEPacketCategoryMeter getInstance() 
	{
		return instance;
	}
	
	public class PacketStat
	{
		private AtomicInteger bytes = new AtomicInteger();
		private AtomicInteger packets = new AtomicInteger();
		
		public AtomicInteger getBytes() {
			return bytes;
		}
		public AtomicInteger getPackets() {
			return packets;
		}		
	}
	
	private SortedMap<Integer,PacketStat> inputPackets = new ConcurrentSkipListMap<Integer,PacketStat> ();
	private SortedMap<Integer,PacketStat> outputPackets = new ConcurrentSkipListMap<Integer,PacketStat> ();
	private Long lastResetTime = null;
	private Map<Integer,PacketStat> copiedInputPackets = new HashMap<Integer,PacketStat>(inputPackets);
	private Map<Integer,PacketStat> copiedOutputPackets = new HashMap<Integer,PacketStat>(inputPackets);
	
	
	public Map<Integer,PacketStat> getInputPackets()
	{
		return copiedInputPackets;
	}
	
	public Map<Integer,PacketStat> getOutputPackets()
	{
		return copiedOutputPackets;		
	}
	
	public void recordInput(int messageType, int len)
	{
		record(this.inputPackets,messageType,len);
	}

	public void recordOutput(int messageType,int messageContentBytes)
	{
		record(this.outputPackets,messageType,messageContentBytes);
	}
	
	private void update()
	{
		copiedInputPackets = new HashMap<Integer,PacketStat>(inputPackets);
		copiedOutputPackets = new HashMap<Integer,PacketStat>(outputPackets);
		inputPackets.clear();
		outputPackets.clear();
		lastResetTime = new Long(System.currentTimeMillis());
	}
	
	private void record(SortedMap<Integer,PacketStat> map, int messageType, int length) 
	{
		PacketStat stat = map.get(messageType);
		if(stat == null)
		{
			stat = new PacketStat();
			map.put(messageType,stat);
		}
		
		stat.getPackets().incrementAndGet();
		stat.getBytes().addAndGet(length);
	}
	
	public Long getLastResetTime()
	{
		return lastResetTime;
	}
}
